package com.jdone.compus.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class BlowSignUtil {
    public static Map<String, Object> buildParams(Map<String, Object> bizParams, String appId, String appKey) {
        Map<String, Object> all = new HashMap<>(bizParams);
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        all.put("app_id", appId);
        all.put("timestamp", now);
        all.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
        // 1. 排序
        List<String> keys = new ArrayList<>(all.keySet());
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (String k : keys) {
            Object v = all.get(k);
            if (v != null) {
                if (sb.length() > 0) sb.append("&");
                sb.append(k).append("=").append(v);
            }
        }
        // 2. 拼接 key
        sb.append(appKey);
        String sign = DigestUtils.md5Hex(sb.toString().getBytes(StandardCharsets.UTF_8)).toUpperCase();
        all.put("sign", sign);
        return all;
    }
}
